<template>
    <div class="container">
        <my-search :fields="fieldsList" :baseNumber="4" @onSearch="searchForm" @onReset="resetForm" />
        <div class="btn">
            <el-button type="info" plain size="mini" @click="go('add')">新增</el-button>
            <el-button type="info" plain size="mini" @click="del()">删除</el-button>

        </div>
        <div class="table-list">
            <my-table v-loading="loading" ref="myEltable" style="width: 100%" row-key="id" :showsummary="false" :columns="tableColumns" :tableData="tableDatas" :pageNum="queryObj.pageNo" :pageSize="queryObj.pageSize" :totalPage="total" :height="$store.state.app.windowHeight - 210" max-height="660px" :current="false" @onCurrentChange="changepageNo" @onPageSizeChange="changePageSize" highlight-current-row :ifSelect="true" @onSelectionChange="onSelectionChange" />
        </div>
        <!-- 上传组件隐藏 -->
        <el-upload style="display:none;" ref="uploadTemplate" class="upload-demo" :before-upload="beforeUpload" action drag :show-file-list="false" :http-request="httpRequest" :multiple="false" accept=".xls, .csv, .xlsx">
            <el-button size="small" type="primary" ref="uploadTemplate_btn">点击上传</el-button>
        </el-upload>
    </div>
</template>

<script>

import { queryList, upload, delete_table, drop_table, add_hyxxk } from '@/api/tzyy/sjkc'

export default {
    name: 'sjkc-list',

    data() {
        return {
            loading: false,
            fieldsList: [
                {
                    label: '数据表',
                    field: 'tableName',
                    type: 'text',
                    value: '',

                },

                {
                    label: '创建日期',
                    field: 'date',
                    type: 'daterange', // daterange
                    value: [],
                    options: [
                        {
                            field: 'startTime',
                            value: ''
                        },
                        {
                            field: 'endTime',
                            value: ''
                        }
                    ],
                    change: value => {
                        // this.changxm(value);
                    }
                },
                {
                    label: '创建人',
                    field: 'createBy',
                    type: 'text',
                    value: '',

                }


            ],
            //右侧表格开始
            tableColumns: [
                {
                    label: '数据表',
                    prop: 'tableName',
                    align: 'center',
                    minWidth: 220,

                },
                {
                    label: '表注释',
                    prop: 'tableComment',
                    align: 'center',
                    minWidth: 220,
                },
                // {
                //     label: '创建日期',
                //     prop: 'createTime',
                //     align: 'center',
                //     minWidth: 150,

                // },
                {
                    label: '创建人',
                    prop: 'createBy',
                    align: 'center',
                    minWidth: 120,

                },

                {
                    label: '数量',
                    prop: 'dataNum',
                    align: 'center',
                    width: 100,
                    render: (h, params) => {
                        // onClick={() => this.upload(params.row)}
                        return (
                            <span class="undertxt" onClick={() => this.go('detail', params.row)}>

                                {params.row.dataNum}

                            </span>
                        );
                    }
                },




                {
                    label: '操作',
                    prop: 'caozuo',
                    align: 'center',
                    width: 150,
                    render: (h, params) => {
                        // onClick={() => this.upload(params.row)}

                        if (params.row.dataNum === 0) {
                            return (
                                <span>

                                    <el-button type="text" onClick={() => this.uploadFile(params.row)}>导入</el-button>
                                    <el-button type="text" onClick={() => this.dropTable(params.row)}>清表</el-button>
                                    <el-button type="text" onClick={() => this.del(params.row)}>删表</el-button>
                                </span>
                            );
                        } else {
                            return (
                                <span>
                                    <el-button type="text" onClick={() => this.dropTable(params.row)}>清表</el-button>
                                    <el-button type="text" onClick={() => this.del(params.row)}>删表</el-button>
                                </span>
                            );
                        }

                    }
                }




            ],
            tableDatas: []
            , queryObj: {
                endTime: '',
                startTime: '',
                createBy: '',
                tableName: '',
                pageNo: 1,
                pageSize: 20
            },
            total: 0,
            selectedRows: [],
            uploadTbaleName: ''

        }
    },

    mounted() {
         this.getTableData();
    },
    methods: {

        searchForm(params) {
            console.log(params, '查询条件');
            this.queryObj.endTime = params.endTime || '';
            this.queryObj.startTime = params.startTime || '';
            this.queryObj.createBy = params.createBy || '';
            this.queryObj.tableName = params.tableName || '';
            this.getTableData();
        },
        resetForm() {
            for (let key in this.queryObj) {
                if (key == 'pageNo') {
                    this.queryObj[key] = 1;
                } else if (key == 'pageSize') {
                    this.queryObj[key] = 20;
                } else {
                    this.queryObj[key] = '';
                }
            }
            this.getTableData();
        },
        getTableData() {
            this.loading = true;
            let params = {
                createBy: this.queryObj.createBy,
                startTime: this.queryObj.startTime,
                endTime: this.queryObj.endTime,
                tableName: this.queryObj.tableName,
                pageNum: this.queryObj.pageNo,
                pageSize: this.queryObj.pageSize,
            }
            queryList(params).then(res => {
                console.log(res)
                this.loading = false;
                if (res.code == 200) {
                    this.tableDatas = res.data.records
                    this.total = res.data.total
                }
            })
        },
        changepageNo(currPage) {
            this.queryObj.pageNo = currPage;
            this.getTableData();
        },
        changePageSize(pageSize) {
            this.queryObj.pageSize = pageSize;
            this.getTableData();
        },
        // 表格 多选 事件
        onSelectionChange(selectedRows) {
            this.selectedRows = selectedRows;
            console.log(selectedRows)
        },
        dropTable(row) {
            this.loading = true;
            this.$confirm('该清表后将不可恢复，是否清表？', '友情提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'JmconfirmCancelButton',
                type: 'warning'
            }).then(() => {
                let ids = []
                ids.push(row.tableName)
               delete_table(ids.join(',')).then(result => {
                    this.loading = false;
                    if (result && result.code == 200) {
                        this.$message.success('清表成功');
                        this.selectedRows = []
                        this.getTableData();
                    } else {
                        this.$message.error('清表失败！');
                    }
                })
                    .catch(error => {
                        this.loading = false;
                    })
            })
        },
        del(row) {
            if (row) {
                this.loading = true;
                this.$confirm('该删除后将不可恢复，是否删除？', '友情提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'JmconfirmCancelButton',
                    type: 'warning'
                }).then(() => {
                    let ids = []
                    ids.push(row.tableName)
                    drop_table(ids.join(',')).then(result => {
                        this.loading = false;
                        if (result && result.code == 200) {
                            this.$message.success('删除成功');
                            this.selectedRows = []
                            this.getTableData();
                        } else {
                            this.$message.error('删除数据失败！');
                        }
                    })
                        .catch(error => {
                            this.loading = false;
                        })
                })
            } else if (this.selectedRows.length > 0) {
                this.loading = true;
                this.$confirm('该删除后将不可恢复，是否删除？', '友情提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'JmconfirmCancelButton',
                    type: 'warning'
                }).then(() => {
                    let ids = []
                    this.selectedRows.forEach(item => {
                        ids.push(item.tableName)
                    })
                    drop_table(ids.join(',')).then(result => {
                        this.loading = false;
                        if (result && result.code == 200) {
                            this.$message.success('删除成功');
                            this.selectedRows = []
                            this.getTableData();
                        } else {
                            this.$message.error('删除数据失败！');
                        }
                    })
                        .catch(error => {
                            this.loading = false;
                        })
                })

            } else {
                this.$message.error('请选择一条数据删除');
                return false;
            }
        },

        uploadFile(row) {
            this.uploadTbaleName = row.tableName
            this.$refs['uploadTemplate'].$refs['upload-inner'].handleClick()
        },
        beforeUpload(file, fileList) {


            if (file.size > 1024 * 1024 * 10) {
                this.$message.warning(
                    "你上传的 \“" + file.name + "\” 文件过大，请上传小于2M的文件。"
                );
                return false;
            }

            if (
                file.name.indexOf("@") != -1 ||
                file.name.indexOf("#") != -1 ||
                file.name.indexOf('""') != -1 ||
                file.name.indexOf("<") != -1 ||
                file.name.indexOf(">") != -1 ||
                file.name.indexOf("?") != -1 ||
                file.name.indexOf("|") != -1 ||
                file.name.indexOf("/") != -1 ||
                file.name.indexOf(":") != -1 ||
                file.name.indexOf("`\`") != -1
            ) {
                this.$message.warning(
                    "你上传的 \“" +
                    file.name +
                    "\” 文件有特殊字符，文件名中不可存在特殊字符,请重新上传"
                );
                return false;
            }

            let index = file.name.lastIndexOf(".");
            let Type = file.name.substr(index + 1, file.name.length);
            if (["xls", "csv", "xlsx"].indexOf(Type.toLowerCase()) === -1) {
                this.$message({
                    type: "warning",
                    message: "请上传后缀名为xls,csv,xlsx的附件！",
                });
                return false;
            }
        },
        httpRequest(data) {
            console.log(data);
            let fd = new FormData();
            fd.append("file", data.file);
            fd.append("tableName", this.uploadTbaleName);
            this.loading = true
            upload(fd).then((res) => {
                this.loading = false
                if (res.code == 200) {
                    this.$message({
                        type: "success",
                        message: res.message,
                    });
                    this.getTableData()
                } else {
                    this.$message({
                        type: "error",
                        message: '导入失败',
                    });
                }
            });
        },
        //待处理
        go(name, params) {
            this.$emit('changePage', name, params);
        },



    }
}
</script>

<style lang="scss" scoped>
.container {
    height: 100%;
    width: 100%;
    background-color: #fff;
    // padding: 8px;

    .btn {
        padding: 8px 8px 8px 0;
    }

    ::v-deep .undertxt {
        color: rgb(64, 158, 255);
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }
    }

    ::v-deep .undertxtRed {
        color: rgb(217, 0, 27);
        cursor: pointer;
        text-decoration: underline;
        &:hover {
        }
    }
}
::v-deep .el-date-editor {
    width: 220px;
}
</style>
